package com.chengwei.ch.busdemo.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.VideoView;

import androidx.constraintlayout.widget.ConstraintLayout;

import com.blankj.utilcode.util.ToastUtils;
import com.chengwei.ch.busdemo.R;
import com.chengwei.ch.busdemo.base.BaseActivity;
import com.chengwei.ch.busdemo.view.CustomVideoView;
import com.gyf.barlibrary.ImmersionBar;
import com.timmy.tdialog.TDialog;
import com.zyl.customkeyboardview.CustomKeyboardEditText;

import static com.chengwei.ch.busdemo.APP.mScreensaver;

@SuppressWarnings("Convert2MethodRef")
public class HomeActivity extends BaseActivity {

    //创建播放视频的控件对象
    private int videoPath;
    private VideoView mVideoView;
    private ConstraintLayout clScanTicketHome, clPersonTicketHome, clIdCardTicketHome;
    private Button btnBuyTicket;
    private int nowtime;
    private TDialog mTDialog = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        initView();
        initClickListener();
        initVideo();
    }


    private void initView() {
        clScanTicketHome = findViewById(R.id.clScanTicketHome);
        clPersonTicketHome = findViewById(R.id.clPersonTicketHome);
        clIdCardTicketHome = findViewById(R.id.clIdCardTicketHome);
        mVideoView = findViewById(R.id.videoView);
        btnBuyTicket = findViewById(R.id.btnBuyTicket);
    }


    private void initClickListener() {
        clScanTicketHome.setOnClickListener(this);
        clPersonTicketHome.setOnClickListener(this);
        clIdCardTicketHome.setOnClickListener(this);
        btnBuyTicket.setOnClickListener(this);
    }

    private void initVideo() {
        //设置将要播放视频文件的加载路径仅支持 3gp、MP4、avi\
        videoPath = R.raw.paly2;
        mVideoView.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" + videoPath));
        //播放
        mVideoView.start();
        //播放准备完毕
        mVideoView.setOnPreparedListener(mp -> {
            mp.setVolume(0f, 0f);
            // mVideoView.start();
        });
        //循环播放
        mVideoView.setOnCompletionListener(mp -> {
            switch (videoPath) {
                case R.raw.paly2: {
                    videoPath = R.raw.paly2;
                    mVideoView.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" + videoPath));
                    break;
                }
                default:
                    break;
            }
            mVideoView.start();
        });
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.clScanTicketHome: {
                showFaceDisDialog();
                break;
            }
            case R.id.clPersonTicketHome: {
                showPersonDisDialog();
                break;
            }
            case R.id.btnBuyTicket: {
                intent.setClass(this, BuyTicketActivity.class);
                startActivity(intent);
                //mScreensaver.resetTime();
                break;
            }
            case R.id.clIdCardTicketHome: {
                showCheckTicketDialog("success");
                //showCheckTicketDialog("fail");
                break;
            }
            default:
                break;
        }
    }

    /**
     * 验票成功或失败弹框
     *
     * @param status = "success" -> 验票成功；status = "failure" -> 验票失败
     */
    private void showCheckTicketDialog(String status) {
        int layoutRes = R.layout.dialog_check_ticket;
        mTDialog = new TDialog.Builder(getSupportFragmentManager())
                .setLayoutRes(layoutRes)    //设置弹窗展示的xml布局
                .setDimAmount(0.6f)
                .setScreenWidthAspect(HomeActivity.this, 0.85f)   //设置弹窗宽度(参数aspect为屏幕宽度比例 0 - 1f)
                .setScreenHeightAspect(HomeActivity.this, 0f)  //设置弹窗高度(参数aspect为屏幕宽度比例 0 - 1f)
                .setOnBindViewListener(viewHolder -> {
                    ImageView ivAllBg = viewHolder.getView(R.id.ivAllBgTicketDialog);
                    TextView tvToast = viewHolder.getView(R.id.tvToastCheckTicketDialog);
                    TextView tvDes = viewHolder.getView(R.id.tvDesCheckTicketDialog);
                    TextView btnAgain = viewHolder.getView(R.id.btnAgainCheckTicketDialog);
                    if (status.equals("success")) {
                        tvDes.setVisibility(View.VISIBLE);
                        btnAgain.setVisibility(View.GONE);
                        ivAllBg.setImageDrawable(getResources().getDrawable(R.mipmap.home_check_ticket_success));
                        tvToast.setText(getResources().getString(R.string.home_check_ticket_success));
                        tvDes.setText(getResources().getString(R.string.home_check_ticket_des));
                    } else {
                        tvDes.setVisibility(View.GONE);
                        btnAgain.setVisibility(View.VISIBLE);
                        ivAllBg.setImageDrawable(getResources().getDrawable(R.mipmap.home_check_ticket_fail));
                        tvToast.setText(getResources().getString(R.string.home_check_ticket_fail));
                        btnAgain.setText(getResources().getString(R.string.home_check_ticket_btn_again));
                    }
                })
                .addOnClickListener(R.id.btnAgainCheckTicketDialog)
                .setOnViewClickListener((viewHolder, view, tDialog) -> {
                    if (view.getId() == R.id.btnAgainCheckTicketDialog) {
                        ToastUtils.showShort("重新验证");
                    }
                })
                .setCancelableOutside(true)
                .create()   //创建TDialog
                .show();    //展示

    }

    /**
     * 人脸识别弹出框
     */
    private void showFaceDisDialog() {
        new TDialog.Builder(getSupportFragmentManager())
                .setLayoutRes(R.layout.dialog_dis_face)    //设置弹窗展示的xml布局
                .setDimAmount(0.6f)
                .setScreenWidthAspect(HomeActivity.this, 0.85f)   //设置弹窗宽度(参数aspect为屏幕宽度比例 0 - 1f)
                .setScreenHeightAspect(HomeActivity.this, 0f)  //设置弹窗高度(参数aspect为屏幕宽度比例 0 - 1f)
                .setOnBindViewListener(viewHolder -> {

                })
                .addOnClickListener(R.id.ivBackFaceDisDialog)
                .setOnViewClickListener((viewHolder, view, tDialog) -> {
                    if (view.getId() == R.id.ivBackFaceDisDialog) {
                        tDialog.dismiss();
                    }
                })
                .setCancelableOutside(true)
                .create()   //创建TDialog
                .show();    //展示
    }

    /**
     * 手动验票
     */
    private void showPersonDisDialog() {
        Dialog dialog = new Dialog(HomeActivity.this);
        dialog.setContentView(R.layout.dialog_dis_person);
        ImageView ivBack = dialog.findViewById(R.id.ivBackPersonDisDialog);
        CustomKeyboardEditText etNameIdCard = dialog.findViewById(R.id.etNameIdCardPersonDisDialog);
        Button btnConfirm = dialog.findViewById(R.id.btnConfirmPersonDisDialog);
        Window window = dialog.getWindow();
        WindowManager.LayoutParams layoutParams = null;
        if (window != null) {
            layoutParams = window.getAttributes();
        }
        assert layoutParams != null;
        layoutParams.gravity = Gravity.CENTER;
        layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
        layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
        window.setBackgroundDrawable(new ColorDrawable());
        dialog.show();
        new Handler().postDelayed(() -> etNameIdCard.showKeyboard(), 100);
        ivBack.setOnClickListener(v -> dialog.dismiss());
        btnConfirm.setOnClickListener(v -> {
            String idCard = etNameIdCard.getText().toString();
            ToastUtils.showShort(idCard);
            dialog.dismiss();
        });

    }


    @Override
    protected void onResume() {
        super.onResume();
        mScreensaver.stop();
        if (mVideoView != null) {
            if (!mVideoView.isPlaying()) {
                mVideoView.seekTo(nowtime);
                mVideoView.start();
            }
        }
    }

    //返回重启加载
    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    protected void onPause() {
        super.onPause();
        nowtime = mVideoView.getCurrentPosition();  //记录当前帧位置int
    }

    //防止锁屏或者切出的时候，音乐在播放
    @Override
    protected void onStop() {
        super.onStop();
        mVideoView.pause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ImmersionBar.with(this).destroy();
        mScreensaver.resetTime();
        mVideoView.stopPlayback();
    }

}
